package com.wanmait.recruitment.webController;

import com.github.pagehelper.PageInfo;
import com.wanmait.recruitment.mapper.CompanyMapper;
import com.wanmait.recruitment.mapper.IndustryMapper;
import com.wanmait.recruitment.pojo.*;
import com.wanmait.recruitment.service.*;
import com.wanmait.recruitment.service.impl.DeliverServiceImpl;
import org.apache.commons.io.FilenameUtils;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpSession;
import java.nio.channels.SeekableByteChannel;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("zhuang")
public class CompanyController {
    @Resource
    private StageService stageService;
    @Resource
    private IndustryService industryService;
    @Resource
    private CityService cityService;
    @Resource
    private CompanyService companyService;
    @Resource
    private JobService jobService;
    @Resource
    private ScaleService scaleService;
    @Resource
    private ProvinceService provinceService;
    @Resource
    private DistrictService districtService;

    @Resource
    private ConfigService configService;

    @Resource
    private CompanyTagService companyTagService;
    @Resource
    private TagsService tagsService;


    @Resource
    private ProductService productService;
    @Resource
    private NatureService natureService;
    @Resource
    private MoneyService moneyService;
    @Resource
    private ExRequireService exRequireService;
    @Resource
    private DegreeService degreeService;
    @Resource
    private ResumeService resumeService;
    @Resource
    private DeliverService deliverService;
    @Resource
    private ResumeStateService resumeStateService;
    @Resource
    private MessageService messageService;
    @Scheduled(cron = "0 0 0 * * ?")
    //@Scheduled(cron = "*/5 * * * * ?")
    public void updateNowJobCount()
    {
        companyService.updateNowJobCount();
    }
    //预览简历
    @RequestMapping("company/preview")
    public void preview(String referer, Integer userId,Integer deliverId, Integer state,Model model)
    {
       if (state==0)
       {
           deliverService.Viewed(deliverId);
           Date date = new Date();
           Timestamp nousedate = new Timestamp(date.getTime());
           ResumeState resumeState = new ResumeState();
           resumeState.setCheck(nousedate);
           resumeStateService.insert(resumeState);
           deliverService.updateResumeState(deliverId,resumeState.getId());
       }
        Resume resume = resumeService.findByResumeId(userId);
        model.addAttribute("resume",resume);

    }
    //待处理简历
    @RequestMapping("company/listpending")
    public void listpending(String state,String pagernum,Integer exRequireId,Integer degreeId, HttpServletRequest request,Model model)
    {
        int pageNum;
        try {
            pageNum =Integer.parseInt(pagernum);
        } catch (NumberFormatException e) {
            pageNum = 1;
        }
        //每页显示条数
        int pageSize;
        try {
            pageSize = Integer.parseInt(configService.getValueByKey("company_resume_count"));
        } catch (Exception e) {
            pageSize = 5;
        }
        HttpSession session = request.getSession();
        Company company = (Company)session.getAttribute("company");
        PageInfo<Deliver>pageInfo = deliverService.pending(pageNum,pageSize,company.getId(),exRequireId,degreeId,Integer.parseInt(state));
        List<Deliver>delivers = pageInfo.getList();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("delivers",delivers);
    }
    //查看待处理简历
    @RequestMapping("company/pending")
    public void pending(HttpServletRequest request,Model model)
    {
        HttpSession session = request.getSession();
        Company company = (Company)session.getAttribute("company");
        List<Degree>degrees = degreeService.findAll();
        List<ExRequire>exRequires = exRequireService.findAll();
        model.addAttribute("exRequires",exRequires);
        model.addAttribute("degrees",degrees);
        Message message = new Message();
        message.setCompanyId(company.getId());
        message.setContent("投递");
        messageService.deleteCompany(message);

    }
    //查看已通过简历
    @RequestMapping("company/haveNoticeResumes")
    public void haveNoticeResumes(String pagernum,HttpServletRequest request,Model model)
    {
        int pageNum;
        try {
            pageNum =Integer.parseInt(pagernum);
        } catch (NumberFormatException e) {
            pageNum = 1;
        }
        //每页显示条数
        int pageSize;
        try {
            pageSize = Integer.parseInt(configService.getValueByKey("company_resume_count"));
        } catch (Exception e) {
            pageSize = 5;
        }
        HttpSession session = request.getSession();
        Company company = (Company)session.getAttribute("company");
        PageInfo<Deliver>pageInfo = deliverService.haveNoticeResumes(company.getId(),pageNum,pageSize);
        List<Deliver>delivers = pageInfo.getList();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("delivers",delivers);
    }
    //设置已通过面试简历
    @RequestMapping("company/adopt")
    @ResponseBody
    public String adopt(Integer id,Integer stat,Integer userId)
    {
        if (stat==null)
        {
            return "0";
        }
        deliverService.adopt(id);
        Date date = new Date();
        Timestamp nousedate = new Timestamp(date.getTime());
        ResumeState resumeState = new ResumeState();
        resumeState.setId(stat);
        resumeState.setAdopt(nousedate);
        resumeStateService.updateAdopt(resumeState);
        Message message = new Message();
        message.setContent("投递");
        message.setUserinfoId(userId);
        messageService.insertResume(message);
        return "1";
    }
    //设置不合适简历
    @RequestMapping("company/inappropriate")
    @ResponseBody
    public String inappropriate(Integer id,Integer stat,Integer uesrId)
    {
        if (stat==null)
        {
            return "0";
        }
        deliverService.inappropriate(id);
        Date date = new Date();
        Timestamp nousedate = new Timestamp(date.getTime());
        ResumeState resumeState = new ResumeState();
        resumeState.setId(stat);
        resumeState.setInappropriate(nousedate);
        resumeStateService.inappropriate(resumeState);
        Message message = new Message();
        message.setContent("投递");
        message.setUserinfoId(uesrId);
        messageService.insertResume(message);
        return "1";
    }
    //查看待定简历
    @RequestMapping("company/canInterviewResumes")
    public void canInterviewResumes(HttpServletRequest request,Model model)
    {
        List<Degree>degrees = degreeService.findAll();
        List<ExRequire>exRequires = exRequireService.findAll();
        model.addAttribute("exRequires",exRequires);
        model.addAttribute("degrees",degrees);
    }
    @RequestMapping("company/listcanInterviewResumes")
    public void listcanInterviewResumes(Integer state,Integer pagernum,Integer exRequireId,Integer degreeId,HttpServletRequest request,Model model)
    {
        int pageNum;
        try {
            pageNum =pagernum;
        } catch (NumberFormatException e) {
            pageNum = 1;
        }
        //每页显示条数
        int pageSize;
        try {
            pageSize = Integer.parseInt(configService.getValueByKey("company_resume_count"));
        } catch (Exception e) {
            pageSize = 5;
        }

        HttpSession session = request.getSession();
        Company company = (Company)session.getAttribute("company");
        PageInfo<Deliver>pageInfo = deliverService.canInterviewResumes(pageNum,pageSize,company.getId(),exRequireId,degreeId,state);
        List<Deliver>delivers = pageInfo.getList();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("delivers",delivers);
    }
    //公司删除简历
    @RequestMapping("company/removed")
    @ResponseBody
    public void removed(Integer id)
    {
        deliverService.removed(id);
    }
    //设置待定简历
    @RequestMapping("company/canInterview")
    @ResponseBody
    public String canInterview(Integer statu,Integer id,Integer userId)
    {
        System.out.println(userId);
        if (statu==null)
        {
            return "0";
        }
            ResumeState resumeState = new ResumeState();
            resumeState.setId(statu);
            Date date = new Date();
            Timestamp nousedate = new Timestamp(date.getTime());
            resumeState.setUndetermined(nousedate);
            resumeStateService.updateUndetermined(resumeState);
            deliverService.canInterview(id);
            Message message = new Message();
            message.setContent("投递");
            message.setUserinfoId(userId);
            messageService.insertResume(message);
            return "1";

    }







    //自动过滤简历
    @RequestMapping("company/autoFilterResumes")
    public void autoFilterResumes(HttpServletRequest request,Model model)
    {

        List<Degree>degrees = degreeService.findAll();
        List<ExRequire>exRequires = exRequireService.findAll();
        model.addAttribute("exRequires",exRequires);
        model.addAttribute("degrees",degrees);

    }

    //简历自动过滤器
    @RequestMapping("company/listAutoFilterResumes")
    public void  listAutoFilterResumes(String state,Integer pagernum,Integer exRequireId,Integer degreeId,  HttpServletRequest request,Model model)
    {
        int pageNum;
        try {
            pageNum =pagernum;
        } catch (NumberFormatException e) {
            pageNum = 1;
        }
        //每页显示条数
        int pageSize;
        try {
            pageSize = Integer.parseInt(configService.getValueByKey("company_resume_count"));
        } catch (Exception e) {
            pageSize = Integer.parseInt(configService.getDefaultValueByKey("company_resume_count"));
        }
        HttpSession session = request.getSession();
        Company company = (Company) session.getAttribute("company");
        Deliver deliver = new Deliver();
        Job job = new Job();
        job.setCompany(company);
        deliver.setJob(job);
        PageInfo<Deliver>pageInfo = deliverService.findPage(pageNum,pageSize,company.getId(),exRequireId,degreeId,Integer.parseInt(state));
        List<Deliver>delivers = pageInfo.getList();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("delivers",delivers);

    }

    //不合适简历
    @RequestMapping("company/haveRefuseResumes")
    public void haveRefuseResumes(String pagernum,HttpServletRequest request,Model model)
    {
        int pageNum;
        try {
            pageNum =Integer.parseInt(pagernum);
        } catch (NumberFormatException e) {
            pageNum = 1;
        }
        //每页显示条数

        int pageSize;
        try {
            pageSize = Integer.parseInt(configService.getValueByKey("company_resume_count"));
        } catch (Exception e) {
            pageSize = Integer.parseInt(configService.getDefaultValueByKey("company_resume_count"));
        }

        HttpSession session = request.getSession();
        Company company = (Company)session.getAttribute("company");
        PageInfo<Deliver>pageInfo = deliverService.inappropriateList(company.getId(),pageNum,pageSize);
        List<Deliver>delivers = pageInfo.getList();
        //List<Deliver>delivers = deliverService.inappropriateList(company.getId());

        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("delivers",delivers);
    }

    //上线职位
    @RequestMapping("company/onlineJob")
    @ResponseBody
    public void onlineJob(Integer id)
    {
        jobService.onlineJob(id);
    }
    @GetMapping("company/offline")
    public void offline(HttpServletRequest request,Model model,String pagernum)
    {
        int pageNum;
        try {
            pageNum =Integer.parseInt(pagernum);
        } catch (NumberFormatException e) {
            pageNum = 1;
        }

        //每页显示条数
        int pageSize;
        try {
            pageSize = Integer.parseInt(configService.getValueByKey("company_resume_count"));
        } catch (Exception e) {
            pageSize = Integer.parseInt(configService.getDefaultValueByKey("company_resume_count"));
        }
        HttpSession session = request.getSession();
        Company company = (Company) session.getAttribute("company");
        //List<Job>jobs = jobService.findOffline(company.getId());
        PageInfo<Job>pageInfo = jobService.findOffline(company.getId(),pageNum,pageSize);
        List<Job>jobs = pageInfo.getList();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("jobs",jobs);
        int JobCount = jobService.findByofflineCount(company.getId());
        model.addAttribute("JobCount",JobCount);
    }

    @PostMapping("company/updateJob")
    public String updateJob(Integer jobId,String name,String industryId,Integer jobNatureId,Integer moneyId,Integer cityId,String degreeId,String exRequireId,String treatment,String describe)
    {
        Industry industry = industryService.findByName(industryId);
        Nature nature = new Nature();
        nature.setId(jobNatureId);
        Money money = new Money();
        money.setId(moneyId);
        City city = cityService.findById(cityId);
        Province province = provinceService.findById(city.getProvince().getId());
        ExRequire exRequire = exRequireService.findByName(exRequireId);
        Degree degree = degreeService.findByName(degreeId);
        Job job = new Job();
        job.setId(jobId);
        job.setName(name);
        job.setIndustry(industry);
        job.setNatures(nature);
        job.setMoney(money);
        job.setCity(city);
        job.setProvince(province);
        job.setExRequire(exRequire);
        job.setDegree(degree);
        job.setTreatment(treatment);
        job.setDescribe(describe);
        Date date = new Date();
        Timestamp nousedate = new Timestamp(date.getTime());
        job.setUpdateTime(nousedate);
        jobService.update(job);
        return "redirect:/zhuang/company/positions";
    }
    //更新职位
    @GetMapping("company/updateJob")
    public void update(String jobId,String OfflineId,HttpServletRequest request,Model model)
    {
        Job job =null;
        if (jobId!=null)
        {
            job = jobService.findById(Integer.parseInt(jobId));
        }
        if (OfflineId!=null)
        {
            job = jobService.findOfflineById(Integer.parseInt(OfflineId));
        }
        model.addAttribute("job",job);
        HttpSession session = request.getSession();
        Company company1 = (Company) session.getAttribute("company");
        Company company = companyService.findById(company1.getId());

        model.addAttribute("company",company);
        List<Industry> industrys = industryService.findAll();
        model.addAttribute("industrys",industrys);
        List<Nature>natures = natureService.findAll();
        model.addAttribute("natures",natures);
        List<Money>moneys = moneyService.findAll();
        model.addAttribute("moneys",moneys);
        List<ExRequire>exRequires = exRequireService.findAll();
        model.addAttribute("exRequires",exRequires);
        List<Degree>degrees = degreeService.findAll();
        model.addAttribute("degrees",degrees);
        List<City>citys= cityService.selectList();
        model.addAttribute("citys",citys);
    }
    //下线职位
    @RequestMapping("company/OfflineJob")
    @ResponseBody
    public void OfflineJob(Integer id)
    {
        jobService.OfflineJob(id);
    }


    @RequestMapping("company/deleteJob")
    @ResponseBody
    public void delete(Integer id)
    {
        jobService.delete(id);
    }
    @RequestMapping("company/positions")
    public void positions(HttpServletRequest request,Model model,String pagernum)
    {
        int pageNum;
       try {
           pageNum = Integer.parseInt(pagernum);
        } catch (Exception e) {
            pageNum=1;
        }
        int pageSize;
        try {
            pageSize = Integer.parseInt(configService.getValueByKey("company_job_count"));
        } catch (Exception e) {
            pageSize = Integer.parseInt(configService.getDefaultValueByKey("company_job_count"));
        }
        //每页显示条数
        HttpSession session = request.getSession();
        Company company = (Company) session.getAttribute("company");
        PageInfo<Job>pageInfo = jobService.findByCompany(company.getId(),pageNum,pageSize);
        List<Job>jobs = pageInfo.getList();
        model.addAttribute("jobs",jobs);
        model.addAttribute("pageInfo",pageInfo);
        int jobCount = jobService.findByCompanyCount(company.getId());
        model.addAttribute("jobCount",jobCount);
    }
    //发布成功页面
    @RequestMapping("company/input_success")
    public void input_success(HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        Company company = (Company) session.getAttribute("company");

    }

    @GetMapping("company/create")
    public void create (HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        Company company1 = (Company) session.getAttribute("company");
        Company company = companyService.findById(company1.getId());
        model.addAttribute("company",company);
        List<Industry> industrys = industryService.findAll();
        model.addAttribute("industrys",industrys);
        List<Nature>natures = natureService.findAll();
        model.addAttribute("natures",natures);
        List<Money>moneys = moneyService.findAll();
        model.addAttribute("moneys",moneys);
        List<ExRequire>exRequires = exRequireService.findAll();
        model.addAttribute("exRequires",exRequires);
        List<Degree>degrees = degreeService.findAll();
        model.addAttribute("degrees",degrees);
        List<City>citys= cityService.selectList();
        model.addAttribute("citys",citys);

    }
    @PostMapping("company/create")
    public String create(HttpServletRequest request,String name,String industry,String jobNature,String moneyId,String cityId,String degree,String exRequire,String treatment,String describe)
    {
        if (name.trim().isEmpty())
        {
            return "redirect:/zhuang/company/create?msg=kong";
        }
        if (moneyId.trim().isEmpty())
        {
            return "redirect:/zhuang/company/create?msg=mkong";
        }
        if (cityId.trim().isEmpty())
        {
            return "redirect:/zhuang/company/create?msg=ckong";
        }
        if (exRequire.trim().isEmpty())
        {
            return "redirect:/zhuang/company/create?msg=ekong";
        }
        if (degree.trim().isEmpty())
        {
            return "redirect:/zhuang/company/create?msg=dkong";
        }
        if (treatment.trim().isEmpty())
        {
            return "redirect:/zhuang/company/create?msg=tkong";
        }
        if (describe.trim().isEmpty())
        {
            return "redirect:/zhuang/company/create?msg=dekong";
        }
        int count = Integer.parseInt(configService.getValueByKey("company_now_job_count"));
        HttpSession session = request.getSession();
        Company company = (Company) session.getAttribute("company");


        if (company.getNowJobCount()>=count)
        {
            return "redirect:/zhuang/company/create?msg=man";
        }
        Job job = new Job();
        job.setCompany(company);
        Industry industry1 = industryService.findByName(industry);
        job.setIndustry(industry1);
        job.setName(name);
        Nature nature = new Nature();
        nature.setId(Integer.parseInt(jobNature));
        job.setNatures(nature);
        Money money = new Money();
        money.setId(Integer.parseInt(moneyId));
        job.setMoney(money);
        City city = cityService.findById(Integer.parseInt(cityId));
        job.setCity(city);
        ExRequire exRequire1 = exRequireService.findByName(exRequire);
        job.setExRequire(exRequire1);
        Degree degree1 = degreeService.findByName(degree);
        job.setDegree(degree1);
        job.setTreatment(treatment);
        job.setDescribe(describe);
        Province province = provinceService.findById(city.getProvince().getId());
        job.setProvince(province);

        jobService.insertList(job);
        companyService.insertNowJobCount(company.getId());
        companyService.insertJobCount(company.getId());
        return "redirect:/zhuang/company/input_success";
    }




    @RequestMapping("company/beEmail")
    @ResponseBody
    public String beEmail(String email,HttpServletRequest request){
        HttpSession session = request.getSession();
        Company loginCompany = (Company)session.getAttribute("company");
        Company company = companyService.findByIdAndEmail(email,loginCompany.getId());
        if(company==null){
            return "0";
        }
        else{
            return "1";
        }
    }
    @GetMapping("company/openstep1")
    public void getOpenstep1(){}

    @PostMapping("company/openstep1")
    public String openstep1(String tel,HttpSession session){
        Company loginCompany = (Company) session.getAttribute("company");
        loginCompany.setTelephone(tel);
        companyService.updateById(loginCompany);
        return "redirect:/zhuang/company/openstep2";
    }
    @GetMapping("company/openstep2")
    public void getOpenstep2(){}
    @PostMapping("company/openstep2")
    public String openstep2(String companyName,HttpSession session){
        Company loginCompany = (Company)session.getAttribute("company");
        if(loginCompany.getCompanyName().equals(companyName)){
            companyService.openCreate(loginCompany.getEmail());
            return "redirect:/zhuang/company/openstep3";
        }
        else{
            return "redirect:/zhuang/company/openstep2?msg=error";
        }
    }
    @GetMapping("company/openstep3")
    public void getOpenstep3(){}
    @RequestMapping("company/openSuccess")
    public void getOpenSuccess(HttpSession session){
        Company loginCompany = (Company)session.getAttribute("company");
        loginCompany.setOpened(true);
        companyService.updateById(loginCompany);
    }
    @RequestMapping("company/reSendOpen")
    public void reSendOpen(HttpSession session){
        Company loginCompany = (Company)session.getAttribute("company");
        companyService.openCreate(loginCompany.getEmail());
    }
    @RequestMapping("company/auth")
    public void auth(){}
    @RequestMapping("company/authSuccess")
    public void authSuccess(){}
    @PostMapping("company/auth")
    public String auth(Company company, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Company loginCompany = (Company) session.getAttribute("company");
        loginCompany.setWebsite(company.getWebsite());
        loginCompany.setCompanyName(company.getCompanyName());
        loginCompany.setLicenseImg(company.getLicenseImg());
        companyService.updateById(loginCompany);
        return "redirect:/zhuang/company/authSuccess";
    }
    @RequestMapping("companylistdata")
    public ModelAndView companyList(HttpServletRequest request,Integer cityId,Integer stageId,Integer industryId,String companyName){

        //页码
        int pageNum;

        try {
            pageNum=Integer.parseInt(request.getParameter("pageNum"));
        } catch (Exception e) {
            pageNum=1;
        }
        //每页显示条数
        int pageSize;
        try {
            pageSize= Integer.parseInt(configService.getValueByKey("web_company_count"));
        } catch (Exception e) {
            pageSize=Integer.parseInt(configService.getDefaultValueByKey("web_company_count"));
        }


        ModelAndView modelAndView=new ModelAndView();
        PageInfo<Company>pageInfo=companyService.findPageAll(pageNum,pageSize,cityId,stageId,industryId,companyName);
        List<Company>companies=pageInfo.getList();
        modelAndView.addObject(pageInfo);
        modelAndView.addObject("companies",companies);
        List<Map> allIndustryList = new ArrayList<>();
        List<Map>allTagsList=new ArrayList<>();

        for (int i=0;i<companies.size();i++) {
            //List<Industry> industryList=industrService.findAllById(companies.get(i).getIndustry().getId());
            List<Job> jobList=jobService.findCompanyByIdTop3(companies.get(i).getId());
            Map<String,Object> map =new HashMap<>();
            map.put("com",companies.get(i).getId());
            map.put("ind",jobList);
            allIndustryList.add(map);

            List<CompanyTag>companyTagList=companyTagService.selectByIdTop3(companies.get(i).getId());
            map.put("coms",companies.get(i).getId());
            map.put("inds",companyTagList);
            allTagsList.add(map);



        }
        modelAndView.addObject("allIndustryList",allIndustryList);
        modelAndView.addObject("allTagsList",allTagsList);

        return  modelAndView;
    }
    @RequestMapping("companylist")
    public ModelAndView companyList (HttpServletRequest request) {
        List<Stage> stageList = stageService.findAll();
        List<Industry> industries = industryService.findHots();
        List<City> cityList = cityService.findAll();
        List<City> cityAF = cityService.selectAF();
        List<City> cityGJ = cityService.selectGJ();
        List<City> cityKN = cityService.selectKN();
        List<City> cityOR = cityService.selectOR();
        List<City> citySV = cityService.selectSV();
        List<City> cityWZ = cityService.selectWZ();
        //List<Company>companies=comPanyService.findAll();
        //页码
        int pageNum;
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("stageList", stageList);
        modelAndView.addObject("industries", industries);
        modelAndView.addObject("cityList", cityList);
        modelAndView.addObject("cityAF", cityAF);
        modelAndView.addObject("cityGJ", cityGJ);
        modelAndView.addObject("cityKN", cityKN);
        modelAndView.addObject("cityOR", cityOR);
        modelAndView.addObject("citySV", citySV);
        modelAndView.addObject("cityWZ", cityWZ);
        return  modelAndView;
    }
    @RequestMapping("company/index01")
    //公司发展阶段
    public ModelAndView index01 () {
        ModelAndView modelAndView = new ModelAndView();
        List<Stage> stages = stageService.findAll();
        modelAndView.addObject("stages", stages);
        List<Scale> scales = scaleService.findAll();
        modelAndView.addObject("scales", scales);
        List<Province> provinces = provinceService.findAll();
        modelAndView.addObject("provinces", provinces);
        List<Industry> industries = industryService.findAllImportant();
        modelAndView.addObject("industries", industries);
        return modelAndView;
    }
    @RequestMapping("company/index02")
    public ModelAndView index02 () {
        ModelAndView modelAndView = new ModelAndView();
        List<Tags> tags = tagsService.findAll();
        modelAndView.addObject("tags",tags);
        return modelAndView;
    }
    @PostMapping("company/index02")
    public String tags(String companyId,String tags){
        companyTagService.insert(Integer.parseInt(companyId),tags);
        return "redirect:/zhuang/company/index03";
    }
    @RequestMapping("company/index03")
    public void index03(){

    }

    @PostMapping("company/index03")
    public String exset(Company company,HttpServletRequest request ){
        HttpSession session = request.getSession();
        Company company1 = (Company) session.getAttribute("company");
        company1.setLegalName(company.getLegalName());
        company1.setInputTime(company.getInputTime());
        companyService.updateById(company1);
        return "redirect:/zhuang/company/index04";
    }
    @RequestMapping("company/index04")
    public void index04(){

    }
    @PostMapping("company/index04")
    public String addCompanyProducts(Products products){
        products.setEnable(true);
        productService.insert(products);
        return "redirect:/zhuang/company/index05";
    }
    @RequestMapping("company/index05")
    public void index05(){

    }
    @PostMapping("company/index05")
    public String addIntroduction(String introduction,HttpServletRequest request){
        HttpSession session = request.getSession();
        Company company = (Company)session.getAttribute("company");
        company.setIntroduction(introduction);
        companyService.updateById(company);
        return "redirect:/zhuang/company/success";
    }
    @RequestMapping("company/success")
    public void success(){

    }
    @RequestMapping("company/myhome")
    public ModelAndView myhome(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        Company company = companyService.selectFindByCompanyById(id);
        modelAndView.addObject("company",company);
        List<Products> products = productService.selectById(id);
        modelAndView.addObject("products",products);
        List<CompanyTag> companyTags = companyTagService.selectById(id);
        modelAndView.addObject("companyTags",companyTags);
        List<Job> jobs = jobService.findByCompanyId(id);
        modelAndView.addObject("jobs",jobs);
        List<Scale> scales = scaleService.findAll();
        modelAndView.addObject("scales",scales);
        List<Province> provinces = provinceService.findAll();
        modelAndView.addObject("provinces",provinces);
        List<Stage> stages = stageService.findAll();
        modelAndView.addObject("stages",stages);
        List<Tags> tags = tagsService.findAll();
        modelAndView.addObject("tags",tags);
        return modelAndView;
    }
    @PostMapping("company/myhome")
    public String updataCompanyMyhomeMassage(Company company){
        companyService.updateById(company);
        return "redirect:/zhuang/company/myhome?id="+company.getId();
    }
    @RequestMapping("company/delecttags")
    public void delecttags(Integer tags,Integer company){
        Company company1 = new Company();
        company1.setId(company);
        Tags tags1 = new Tags();
        tags1.setId(tags);
        CompanyTag companyTag = new CompanyTag();
        companyTag.setCompany(company1);
        companyTag.setTags(tags1);
        companyTagService.update(companyTag);
    }
    @PostMapping("company/updateCompanyImg")
    public String updateCompanyImg(MultipartFile file,Company company,HttpServletRequest request){
        String fileName = "";
        if (file!=null&&!file.isEmpty()){
            //原文件名
            String oldFileName = file.getOriginalFilename();
            //获得扩展名
            String ext = FilenameUtils.getExtension(oldFileName);
           /* if(!",jpg,jpeg,png,gif,".contains(","+ext+",")){
                return "redirect:/hello?msg=ext";
            }
            if(file.getSize()>1024000*5){
                return "redirect:/hello?msg=size";
            }*/
            //新的文件名
            fileName = UUID.randomUUID()+"."+ext;
            //获得物理路径
            String realPath = request.getServletContext().getRealPath("/static/uploadImg");
            File outFile = new File(realPath,fileName);
            try {
                //保存文件
                file.transferTo(outFile);
                //添加到对象中
                company.setLogo(fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        companyService.updateById(company);
        return "redirect:/zhuang/company/myhome?id="+company.getId();
    }
    @PostMapping("company/updateProduct")
    public String updateProduct(Products products,MultipartFile productFile,HttpServletRequest request){
        HttpSession session = request.getSession();
        Company company = (Company)session.getAttribute("company");
        if (!productFile.isEmpty()){
            String oldFileName = productFile.getOriginalFilename();
            String ext = FilenameUtils.getExtension(oldFileName);
            if(!",jpg,jpeg,png,gif,".contains(","+ext+",")){
                return "redirect:/zhuang/company/myhome?id="+company.getId()+"&mes=ext";
            }
            if(productFile.getSize()>1024000*5){
                return "redirect:/zhuang/company/myhome?id="+company.getId()+"&mes=size";
            }
            String fileNewName = UUID.randomUUID()+"."+ext;
            String path = request.getServletContext().getRealPath("/static/uploadImg");
            File outFile = new File(path,fileNewName);
            try {
                productFile.transferTo(outFile);
                products.setImg(fileNewName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            productService.update(products);
            return "redirect:/zhuang/company/myhome?id="+company.getId();
        }
        else {
            productService.update(products);
            return "redirect:/zhuang/company/myhome?id="+company.getId();
        }
    }
    @RequestMapping("company/productDelete")
    public String productDelete(Integer id,HttpServletRequest request){
        productService.updateEnable(id);
        HttpSession session = request.getSession();
        Company company = (Company)session.getAttribute("company");
        return "redirect:/zhuang/company/myhome?id="+company.getId();
    }
    @PostMapping("company/addProduct")
    public String addProduct(Products products,MultipartFile productFile,HttpServletRequest request){
        if (!productFile.isEmpty()){
            String oldFileName = productFile.getOriginalFilename();
            String ext = FilenameUtils.getExtension(oldFileName);
            if(!",jpg,jpeg,png,gif,".contains(","+ext+",")){
                return "redirect:/zhuang/company/myhome?id="+products.getCompany().getId()+"&mes=ext";
            }
            if(productFile.getSize()>1024000*5){
                return "redirect:/zhuang/company/myhome?id="+products.getCompany().getId()+"&mes=size";
            }
            String fileNewName = UUID.randomUUID()+"."+ext;
            String path = request.getServletContext().getRealPath("/static/uploadImg");
            File outFile = new File(path,fileNewName);
            try {
                productFile.transferTo(outFile);
                products.setImg(fileNewName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            productService.save(products);
            return "redirect:/zhuang/company/myhome?id="+products.getCompany().getId();
        }
        else {
            productService.save(products);
            return "redirect:/zhuang/company/myhome?id="+products.getCompany().getId();
        }
    }
    @PostMapping("company/updateCompanyMes")
    public String updateCompanyMes(Company company,String provinceName, String cityName, String districtName){
        if (provinceName==""&&cityName==""&&districtName==""){
            companyService.updateById(company);
            return "redirect:/zhuang/company/myhome?id="+company.getId();
        }
        else {
            company.setAddress(provinceName+cityName+districtName+company.getAddress());
            companyService.updateById(company);
            return "redirect:/zhuang/company/myhome?id="+company.getId();
        }
    }
    @RequestMapping("company/addTags")
    public String addTags(String tagsIds,Integer id){
        companyTagService.insert(id,tagsIds);
        return "redirect:/zhuang/company/myhome?id="+id;
    }
    @RequestMapping("city")
    @ResponseBody
    public String city ( int privonceId){
        List<City> cityList = cityService.selectByProvinceId(privonceId);
        String citys = "";
        for (City city : cityList) {
            citys = citys + "," + city.getId() + ":" + city.getCityName();
        }
        return citys;
    }
    @RequestMapping("district")
    @ResponseBody
    public String district ( int cityId){
        List<District> districtList = districtService.findByCityId(cityId);
        String districts = "";
        for (District district : districtList) {
            districts = districts + "," + district.getId() + ":" + district.getDistrictName();
        }
        return districts;
    }
    @PostMapping("/addCompanyMessage1")
    public String addCompanyMessage1 (Company company,HttpServletRequest request, String provinceName, String cityName, String districtName){
        HttpSession session = request.getSession();
        Company company1 = (Company)session.getAttribute("company");
        company1.setEnable(true);
        company1.setAddress(provinceName + cityName + districtName + company.getAddress());
        company1.setCompanyAbbreviation(company.getCompanyAbbreviation());
        City city = new City();
        city.setId(company.getCity().getId());
        company1.setCity(city);
        Industry industry = new Industry();
        industry.setId(company.getIndustry().getId());
        company1.setIndustry(industry);
        Scale scale = new Scale();
        scale.setId(company.getScale().getId());
        company1.setScale(scale);
        Stage stage = new Stage();
        stage.setId(company.getStage().getId());
        company1.setStage(stage);
        company1.setLogo(company.getLogo());
        if (company.getIndustry().getId() == null || company.getScale().getId() == null || company.getStage().getId() == null) {
            return "redirect:/zhuang/company/index01?error=mes";
        } else {
            companyService.updateById(company1);
            return "redirect:/zhuang/company/index02";
        }
    }
}


